package org.streets.eis.setting.auth;

import org.apache.wicket.Component;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.streets.commons.util.ClassUtils;

import org.streets.eis.EisWebSession;
import org.streets.eis.setting.auth.annotations.UserSecurity;
import org.streets.eis.entity.User;
import org.streets.eis.pages.BasePage;

public class UserPermitStrategy implements IAuthorizationStrategy {

	private final UserPermitAuthorizer authorizer;
	
	public UserPermitStrategy(UserPermitAuthorizer authorizer) {
		this.authorizer = authorizer;
	}
	
	public boolean isActionAuthorized(Component component, Action action) {
		// we do not authorize action or component
		// include ENABLE & RENDER 
		return true;
	}

	public <T extends Component> boolean isInstantiationAuthorized(Class<T> component) {
		// 跳过非页面级别的检查
		if (! ClassUtils.isSubclassOf(component, BasePage.class)) {
			return true;
		}
				
		User user = EisWebSession.get().getUser();
		if (user == null) return false; 
		
		UserSecurity rs = component.getAnnotation(UserSecurity.class);

		String expr = rs == null ? "" : rs.value();
		
		return authorizer.authorized(user, expr);
	}
}
